<?php
class AssetIndexController  extends Zone_Action{
	public function fields(){
		$data = array(
			date_updated =>array(
				type			=> 'NONE',
				default_value   => new Model_Expr('NOW()')
			),			
			updated_by_id =>array(
				type			=>	'NONE',
				default_value 	=>	get_user_id()
			),
		
			code 	=> array(
				type 		=> 'CHAR',
				form_label	=> 'Mã khách hàng',	
				default_value=>null				
			),
			codesu 	=> array(
				type 		=> 'CHAR',
				form_label	=> 'Mã bảo hành',	
				default_value=>null				
			),
			
			title 	=> array(
				type 		=> 'TEXT',
				no_empty 	=>true,
				form_label	=> 'Tên tài sản',
			),
			model	=>array(
				type		=>'TEXT',
				form_label	=>'Model'
			),
			origin =>array(
				type		=>'CHAR',
				form_label 	=>'Hãng sản xuất',
				no_empty 	=>true
			),
			value =>array(
				type		=>'CHAR',
				form_label 	=>'Giá trị',
				
			),
			mtype =>array(
				type		=>'CHAR',
				form_label 	=>'Loại tiền tệ',
				
			),
			datebuy =>array(
				type		=>'DATE',
				fix_value	=> change_date_format,
				form_label 	=>'Ngày mua',
				no_empty 	=>true,
				default_value=>null
			),
			time =>array(
				type			=>'DATE',
				fix_value	=> change_date_format,
				form_label 		=>'Bảo hành đến',
				default_value=>null
			),
			buyat =>array(
				type			=>'TEXT',
				form_label		=>'Địa điểm mua',
				default_value=>null
			),
			asset_type_id =>array(
				type			=>'INT',
				form_label		=>'Loại tài sản',
			),
			status =>array(
				type			=>'CHAR',
				form_label		=>'Tình trạng',
				
			),
			desc =>array(
				type			=>'HTML',
				form_label		=>'Mô tả',
				default_value=>null
			),
			date_tranfer =>array(
				type			=>'DATETIME',
				default_value   =>date("Y-m-d H:i:s"),
				form_label		=>'Ngày bàn giao mới'
			)
		);
		return $data;	
	}
	
	public function Transfers($default=NULL){
		$data = array(
			code_transfers 	=> array(
				type 		=> 'CHAR',
				form_label	=> 'Mã bàn giao',	
				no_empty =>true,				
			),
			asset_id 	=> array(
				type 		=> 'INT',
				form_label	=> 'Tài sản id',	
				default_value=>null				
			),
			department_id 	=> array(
				type 		=> 'INT',
				form_label	=> 'Mã khách hàng',	
				default_value=>null				
			)
		);
		/* Neu chinh sua thi cac thong so duoc mac dinh trc */
		if(is_array($default)){
			foreach( $data as $k => $config ){
				if( $config['type'] != 'NONE' && isset( $default[$k] ) ){
					$data[$k]['default_value'] = $default[$k];
				}
			}
		}	
		return $data;	
	}
	
	public function transferAction(){
		$this->removeLayout();
		$asset_id = getInt("ID",0);
		$this->set(array(
			"asset_id" =>$asset_id
		));
		$checkStatus = $this->Model->fetchRow("SELECT * FROM `assets` WHERE `ID`='$asset_id'");
		if($checkStatus["status"]=="dont"){
			return $this->setJSON(array(
					alert => error("Tình trạng tài sản không thể tiếp tục sử dụng")
			));
		}
		if(isPost()){
			$asset_id = $_POST["asset_id"];
			loadClass("ZData");
			$form = new ZData();
			$form->addFields( $this->Transfers());
			$data = $form->getData();
			if( is_array($data)){
				$data["created_by_id"] = get_user_id();
				$data["date_created"] = mysql_date();
				$this->Model->insert('assets_transfers',$data);
				$lastTransfer = $this->Model->lastId();
				$users = (array)$_POST['users'];
				for($i=0;$i<count($users);$i++){
					$this->Model->insert("assets_users",array(
						asset_id	=> $asset_id,
						user_id 	=> $users[$i],
						transfer_id => $lastTransfer
					));
				}
				return $this->setJSON(array(
					redirect => "#Asset/Index/View?ID=".$asset_id
				));
			}else{
				return $this->setJSON(array(
					message => error($data)
				));
			}
		}
	}
	
	public function initAction(){
		if(!$this->hasRole("crm")){
			return $this->setContent(error("Bạn không có quyền truy cập tài sản. "));
		}
		$departments = $this->Model->fetchAll("SELECT * FROM `departments` ORDER BY `parent_id`");
		$this->set(array(
			type 			=>$this->Model->fetchAll("SELECT * FROM `assets_types`"),
			treeDepartment	=>$departments
		));
	}
	
	public function indexAction(){
		$type= getInt("type",0);
		$user_id = get_user_id();
		$vars = array();
		if($type!=0){
			$vars['type'] = $type;
			$condition = " AND `asset_type_id`='$type'";
			$this->set('title',$this->Model->fetchOne("SELECT title FROM `assets_types` where `ID`='$type'"));
			
		}
		
		$WHERE = array();
		$order_by = " ORDER BY title DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p'])){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('title','origin','department_id','status','datebuy');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		$total = $this->Model->fetchOne("SELECT COUNT(*) FROM `assets` WHERE `is_draft`='no' $condition");
		$posts = $this->Model->fetchAll("
			SELECT 
				`a`.*,
				GROUP_CONCAT( IF(`d`.`is_deleted`='yes','deleted', CONCAT('<a class=\"userlink\" href=\"#User/Info?ID=',`d`.`ID`,'\">',`d`.`username`,'</a>')) SEPARATOR ', ') as `using_count`
			FROM `assets` as `a` 
				
				LEFT JOIN `assets_users` as `c` 
					ON `c`.`asset_id`=`a`.`ID`
				LEFT JOIN `users` as `d`
					ON `d`.`ID`=`c`.`user_id`
			WHERE 
				`a`.`is_draft`='no' $condition 
			GROUP BY `a`.`ID`
			$order_by $limit");
		
		$a = $vars;
		// print_r($vars);
		// exit;
		unset($a['p']);
		
		$page = page_ajax('#Asset?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			user_id	=> get_user_id(),
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			post	=> $posts
			
		));
	}

	public function changestatusAction(){
		$asset_id = getInt("ID",0);
		$r = $this->Model->fetchRow("SELECT * FROM `assets` WHERE `ID`='$asset_id'");
		if($r["status"]=="using"){
			$st = "dont";
		}else{
			$st = "using";
		}
		
		$arr = array("status" => $st);
		$this->Model->update("assets",$arr," `ID`='$asset_id'");
		return $this->setJSON(array(
			redirect => "#Asset/Index/View?ID=".$asset_id
		));
	}
	
	public function uploadAction(){
		$this->removeLayout();
		$asset_id = getInt("asset_id",0);
		
		$user_id = get_user_id();
		if( isPost()){
			loadClass("ZData");
			$f = new ZData();
			$f->addField(array(
				file => array(
					type 		=> 'FILE',
					path		=> 'files/asset/',
					no_empty	=> true
				)
			));
			
			$data = $f->getData();
			if( is_array( $data ) ){
				$file = $data['file'];
				$this->Model->insert("assets_files",array(
					asset_id	=> $asset_id,
					name				=> $file[0],
					type				=> $file[1],
					size				=> $file[2],
					filename			=> $file[3]
				));
				
				$file_id = $this->Model->lastId();				
				return $this->setJSON(array(
					content	=> "<div class='x-file-info'><input checked type='checkbox' name='files[]' value='$file_id'/>
								<a href='".ctrUrl($this)."/File?ID=$file_id' target='_blank'>{$file[3]} {$file[2]} KB	</a>
								</div>"
				));
			}else{
				return $this->setJSON(array(
					alert => error($data)
				));				
			}
		}
	}
	
	public function addAction(){
		$user_id = get_user_id();
		if( !isPost() ){	
			$post = $this->Model->fetchRow("SELECT * FROM `assets` WHERE `created_by_id`='$user_id' AND `is_draft`='yes' LIMIT 1");
			
			if($post){
				$post_id = $post['ID'];
			}else{
				$this->Model->insert('assets',array(
					is_draft		=> 'yes',
					created_by_id	=> $user_id			
				));
				$post_id = $this->Model->lastId();
			}
			
			$this->set('ID',$post_id);
		}
		
		if(isPost()){
			$post_id = getInt('ID',0);
			$post = $this->Model->fetchRow("SELECT * 
				FROM `assets` WHERE `created_by_id`='$user_id' LIMIT 1");
			
			if(!$post){
				return $this->setContent(error('Bản ghi đã bị xóa hoặc không tồn tại'));
			}	
		
			loadClass('ZData');
			
			$f = new ZData();
			$f->addFields( $this->fields());
			$data = $f->getData();
			
			if( !is_array( $data ) ){
				return $this->setJSON(array(
					message	=> error($data)
				));
			}
				
			$data['date_created'] = new Model_Expr('NOW()');
			$data['is_draft'] = 'no';
			
			$this->Model->update('assets',$data,"`ID`='$post_id'");
			
			return $this->setJSON(array(
				redirect	=> '#Asset'
			));
		}
	}
	
	public function editAction(){
		$user_id = get_user_id();
		$asset_id = getInt('ID',0);
		$post = $this->Model->fetchRow("
			SELECT `a`.* FROM `assets` as `a` 
			
			WHERE `a`.`ID`='$asset_id'");
		
		
		$files = $this->Model->fetchAll("SELECT * FROM `assets_files` where `asset_id`='$asset_id'");
		$this->set(array(
			posts				=> 	$post,
			asset_id 			=>	$asset_id,
			files				=> 	$files
		));
		if(isPost()){
			loadClass("ZData");
			$asset_id = $_POST["asset_id"];
			$users = (array)$_POST['users'];
			$form = new ZData();
			$form->addFields( $this->Fields($post));
			$data = $form->getData();
			if( is_array($data)){
				$this->Model->delete("assets_users","`asset_id`='$asset_id'");
				if($post["created_by_id"]==null){
					$data['created_by_id'] = get_user_id();
					$data['date_created']  = date("Y-m-d H:i:s");
				}
				$data['is_draft']='no';
				$this->Model->update("assets",$data,"`ID`='$asset_id'");
				for($i=0;$i<count($users);$i++){
					$this->Model->insert("assets_users",array(
						asset_id	=>$asset_id,
						user_id 			=>$users[$i],
					));
				}
				$files_selected = (array)$_POST['files'];
				$files = $this->Model->fetchAll("SELECT * FROM `assets_files` WHERE `asset_id`='$asset_id'");
				foreach( $files as $f ){
					if( !in_array( $f['ID'], $files_selected ) ){
						$this->Model->delete("assets_files","`ID`='{$f['ID']}'");
						@unlink("files/asset/{$f['name']}");
					}
				}
				return $this->setJSON(array(
					redirect	=> "#asset/Index/View?ID=".$asset_id
				));
			}else{
				return $this->setJSON(array(
					message => error($data)
				));
			}			
		}
	}
	
	public function viewAction(){
		$id=getInt('ID',0);
		$post  = $this->Model->fetchRow("
		SELECT `a`.*,`b`.`title` as `asset_type_title`,`d`.`username` as `updated_by_name`,`d`.`is_deleted` as `updated_is_deleted` FROM `assets` as `a`
			LEFT JOIN `assets_types` as `b` ON `b`.`ID`=`a`.`asset_type_id`
			LEFT JOIN `users` as `d` ON `d`.`ID`=`a`.`created_by_id`
		WHERE `a`.`ID`='$id'
		");
		$file = $this->Model->fetchAll("SELECT * FROM `assets_files` WHERE `asset_id`='$id'");
		
	
		$transfers = $this->Model->fetchAll("
			SELECT `a`.*,`b`.`username` as `created_by_name`,`c`.`title` as `depart_name`
			FROM `assets_transfers` as `a`
				LEFT JOIN `users` as `b` ON `b`.`ID`=`a`.`created_by_id`
				LEFT JOIN `departments` as `c` ON `c`.`ID`=`a`.`department_id`
			WHERE `a`.`asset_id`='$id' ORDER BY `a`.`ID` DESC
			
		");
		
		foreach( $transfers as $k => $a ){
			$users = $this->Model->fetchAll("SELECT `a`.* FROM `users` as `a` 
				LEFT JOIN `assets_users` as `b`
				ON `a`.`ID`=`b`.`user_id` AND `b`.`transfer_id`='{$a['ID']}' 
				WHERE `b`.`transfer_id` IS NOT NULL");
			$transfers[$k]['users'] = $users;	
		}
		
		
		$this->set(array(
            post      			=>$post,
			files 				=>$file,
			transfers			=>$transfers,
			user_id				=>get_user_id()
        ));
	}	
	
	public function deletetranfersAction(){
		$id = getInt("ID",0);
		$asset_id = getInt("asset_id",0);
		$this->Model->delete("assets_transfers","`ID`='$id'");
		$this->Model->delete("assets_users","`transfer_id`='$id'");
		return $this->setJSON(array(
			redirect =>"#Asset/Index/View?ID=".$asset_id
		));
	}
	
	public function deleteAction(){
		$id=getInt("ID",0);
		$user_id = get_user_id();
		if($id!=0){
			$check = $this->Model->fetchRow("SELECT * FROM `assets` WHERE `ID`='$id'");
			if($check['created_by_id']!=get_user_id()){
				return $this->setJSON(array(
					alert =>error('Bạn không có quyền xóa tài sản này')
				));
			}
			$files = $this->Model->fetchAll("SELECT * FROM `assets_files` WHERE `asset_id`='$id'");
			foreach( $files as $file ){
				@unlink("files/asset/{$file['name']}");
			}
			$this->Model->delete("assets"," `ID`='$id' ");
			$this->Model->delete("assets_users","`asset_id`='$id'");
			$this->Model->delete("assets_files","`asset_id`='$id'");
			$this->Model->delete("assets_transfers","`asset_id`='$id'");
		}else{
			$ids = $_POST["ID"];
			if(empty($ids)==true){
				return $this->setJSON(array(
						alert =>error('Chưa có tài sản nào được chọn.')
					));
			}
			foreach($ids as $vid){
				$created_by_id = $this->Model->fetchOne("SELECT `created_by_id` FROM `assets` WHERE `ID`='$vid'");
				if($created_by_id!=$user_id){
					return $this->setJSON(array(
						alert =>error('Có tài sản không được quyền xóa')
					));
				}else{
					$files = $this->Model->fetchAll("SELECT * FROM `assets_files` WHERE `asset_id`=$vid");
					foreach( $files as $file ){
						@unlink("files/asset/{$file['name']}");
					}
				}
			}
			$strID = "(".join(",",$ids).")";
			$this->Model->delete("assets","`ID` in $strID");	
			$this->Model->delete("assets_users","`asset_id` in $strID");	
			$this->Model->delete("assets_files","`asset_id` in $strID");	
			$this->Model->delete("assets_transfers","`asset_id` in $strID");	
		}
		return $this->setJSON(array(
			redirect	=> "#asset"
		));
	}
	
	public function fileAction(){
		$file_id = get('ID',0);
		$user_id = get_user_id();
		$file = $this
			->Model->fetchRow("SELECT * FROM `assets_files` as `a` WHERE `a`.`ID`='$file_id' LIMIT 1");
		
		$file_path = "files/asset/{$file['name']}";
		
		if( !file_exists( $file_path ) ){
			return $this->setError('404');
		}	
		if( get('type') == 'icon' ){	
			$img_types = array('image/gif','image/png','image/x-png','image/jpeg','image/x-jpeg','image/jpg');
			if( in_array($file['type'],$img_types) ){
				loadClass('PHPThumb');
				$thumb = PhpThumbFactory::create($file_path);
				$thumb->resize(60, 60);
				$thumb->show();
			}else{
				@readfile("files/static/icon.gif");	
			}		
		}else if( get('type') == 'view' ){	
			$img_types = array('image/gif','image/png','image/x-png','image/jpeg','image/x-jpeg','image/jpg');
			if( in_array($file['type'],$img_types) ){
				loadClass('PHPThumb');
				$thumb = PhpThumbFactory::create($file_path);
				$thumb->show();
			}else{
				@readfile("files/static/icon.gif");	
			}		
		}else{
			@header("Content-Disposition: attachment; filename={$file['name']}");
			@readfile($file_path);
		}
	}
	
 	function sendMessage($user_id, $content ){
 		for($i=0;$i<count($user_id);$i++){
			$this->Model->insert("notices",array(
				created_by_id   =>get_user_id(),
				user_id			=> $user_id[$i],
				content			=> $content,
				date			=> date("Y-m-d H:i:s",time())
			));
 		}
	}
	
}
?>